package com.xiongmao.webflux.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xiongmao.webflux.common.ResponseData;
import org.reactivestreams.Publisher;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author: lao_hu
 * @Date: 2022/2/25 14:25
 * @Description:
 */
@Component
public class JsonHttpMessageWriter implements HttpMessageWriter<Map<String, Object>> {
    @NonNull
    @Override
    public List<MediaType> getWritableMediaTypes() {
        return Collections.singletonList(MediaType.APPLICATION_JSON);
    }

    @Override
    public boolean canWrite(@NonNull ResolvableType elementType, MediaType mediaType) {
        return MediaType.APPLICATION_JSON.includes(mediaType);
    }

    @NonNull
    @Override
    public Mono<Void> write(@NonNull Publisher<? extends Map<String, Object>> inputStream,
                            @NonNull ResolvableType elementType,
                            MediaType mediaType,
                            @NonNull ReactiveHttpOutputMessage message,
                            @NonNull Map<String, Object> hints) {
        return Mono.from(inputStream).flatMap(m -> message.writeWith(Mono.just(message.bufferFactory().wrap(transform2Json(m)))));
    }

    private byte[] transform2Json(Map<String, Object> sourceMap) {
        byte[] stream;
        ResponseData<Object> objectResponseData;
        try {
            Object data = sourceMap.getOrDefault("data", "");
            int code = (int)sourceMap.getOrDefault("code", 500);
            String msg = (String)sourceMap.getOrDefault("error", "ERROR");
            stream = JSON.toJSONString(ResponseData.restResult(data,code,msg), SerializerFeature.WriteMapNullValue).getBytes("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            stream = JSON.toJSONString(ResponseData.fail(), SerializerFeature.WriteMapNullValue).getBytes();
        }
        return stream;
    }
}
